package com.situ.mall.admin.controller;


import com.situ.mall.admin.entity.Attachment;
import com.situ.mall.admin.service.IAttachmentService;
import com.situ.mall.admin.util.StringUtil;
import com.situ.mall.common.entity.Category;
import com.situ.mall.common.service.ICategoryService;
import com.situ.mall.common.vo.LayuiTableVO;
import com.situ.mall.common.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author membergpf
 * @since 2023-03-22
 */
@Controller
@RequestMapping("/category")
public class CategoryController {

@Autowired
private IAttachmentService attachmentService;
    @Autowired
    private ICategoryService categoryService;
    @GetMapping("/page")
    public String page(){
        return "category";
    }
    @GetMapping("/list")
    @ResponseBody
    public LayuiTableVO list(){

        return  categoryService.doList();
    }
    @PostMapping("/del")
    @ResponseBody
    public void delete(Integer id){
        categoryService.del(id);
    }
    @GetMapping("/{id}")
    @ResponseBody
    public Category selectById(@PathVariable("id") Integer id){
        return categoryService.getById(id);
    }
    @PostMapping("/save")
    @ResponseBody
    public void save(Category menu){
        categoryService.saveOrUpdate(menu);

    }
    @PostMapping("/attach")
    @ResponseBody
    public ResultVO avatar(MultipartFile file) {
        ResultVO vo = new ResultVO();
        vo.setMsg("上传成功");
        String fileName =System.currentTimeMillis() + ".png";
        File f = new File("D:\\test\\" + fileName);
        try {
            file.transferTo(f);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        System.out.println("接收到请求");
        String src ="/upload/"+fileName;

        Attachment attachment = new Attachment();
        attachment.setPath(src);
        attachment.setFileName(file.getOriginalFilename());
        //使用String工具类吧long类型的文件大小转化字符串类型的
        attachment.setFileSize(StringUtil.formatFileSize(file.getSize()));
        attachment.setType(file.getContentType());
        attachment.setCreatetime(LocalDateTime.now());
        Integer id = attachmentService.insert(attachment);

        Map<String, Object> map = new HashMap<>();
        map.put("src", src);
        map.put("id",id);
        vo.setData(map);
        return vo;
    }
    @GetMapping("/firstName")
    @ResponseBody
    public List<Category> firstName(){
        return categoryService.firstName();
    }
    @PostMapping("/second")
    @ResponseBody
    public List<Category> secondName(Integer id){
        return categoryService.secondName(id);
    }
}
